from openai import OpenAI
import os

# 配置 API 相关信息
API_KEY = "sk-565505bad9db4ea086eb6d45b8bdd1bc"
BASE_URL = "https://api.deepseek.com"

# 创建 Client
client = OpenAI(api_key=API_KEY, base_url=BASE_URL)

# 消息历史记录，用于保持上下文
messages = []

def stream_chat():
    print("喵～和 DeepSeek 聊天吧！输入 'bye' 退出\n")

    while True:
        # 用户输入
        user_input = input("你：")
        if user_input.lower() in ["bye", "exit", "quit"]:
            print("猫娘挥爪爪再见喽~ 🐾")
            break

        # 添加用户消息
        messages.append({"role": "user", "content": user_input})

        # 发起流式请求
        print("DeepSeek：", end="", flush=True)
        response = client.chat.completions.create(
            model="deepseek-chat",
            messages=messages,
            stream=True  # 开启流式输出
        )

        full_response = ""
        for chunk in response:
            if chunk.choices[0].delta.content:
                content_part = chunk.choices[0].delta.content
                print(content_part, end="", flush=True)
                full_response += content_part
        print()  # 换行

        # 保存 assistant 的回复到历史消息
        messages.append({"role": "assistant", "content": full_response})


if __name__ == "__main__":
    stream_chat()
